package cn.itcast.web.exception;

import org.apache.shiro.authz.UnauthorizedException;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 实现HandlerExceptionResolver接口
 * 将异常处理器交给容器
 */
@Component
public class SaasExceptionHandler implements HandlerExceptionResolver {


    /**
     * 处理异常
     *    参数：
     *      Exception  当前抛出的异常
     *    需求：
     *      权限不足的时候，跳转到权限不足页面（unauthorized.jsp）
     *       UnauthorizedException
     *    思路：
     *      判断，当前捕获的异常是否为UnauthorizedException
     */
    public ModelAndView resolveException(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception ex) {
        ex.printStackTrace();
        if(ex instanceof UnauthorizedException) {
            ModelAndView mv = new ModelAndView();
            mv.setViewName("forward:/unauthorized.jsp");
            return mv;
        } else{
            ModelAndView mv = new ModelAndView();
            mv.setViewName("error");
            mv.addObject("errorMsg", "对不起，我错了");
            mv.addObject("ex", ex);
            return mv;}
    }
}
